#include "scanner.h"
#include <QDir>
#include <QDebug>
#include <QElapsedTimer>
#include <windows.h>
//--------------------- ScanTask 实现 ---------------------
class ScanTask : public QRunnable {
public:
    // 任务完成后自动删除
    ScanTask(FileScanner* scanner, const QString& path)
        : m_scanner(scanner), m_path(path)
    {
        setAutoDelete(true);
    }


    void run() override {
        if (m_scanner->isStopRequested()) return;

        // Windows路径安全处理
        QString searchPath = m_path;
        if (!searchPath.endsWith("\\*")) {
            searchPath = QDir::toNativeSeparators(searchPath);
            if (!searchPath.endsWith("\\")) searchPath += "\\";
            searchPath += "*";
        }

        WIN32_FIND_DATAW findData;
        HANDLE hFind = FindFirstFileW(searchPath.toStdWString().c_str(), &findData);
        if (hFind == INVALID_HANDLE_VALUE) {
            qWarning() << "无法打开目录:" << searchPath << "错误代码:" << GetLastError();
            return;
        }

        QList<FileResult> batch;
        QString parentPath = searchPath.left(searchPath.lastIndexOf('*')).trimmed();
        if (!parentPath.endsWith('\\')) parentPath += '\\';

        do {
            if (m_scanner->isStopRequested()) break;

            const QString fileName = QString::fromWCharArray(findData.cFileName);
            if (fileName == "." || fileName == "..") continue;

            const QString fullPath = parentPath + fileName;

            // 目录处理逻辑优化
            if (findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                QString childPath = parentPath + fileName + "\\*"; // 确保通配符格式
                m_scanner->submitTask(new ScanTask(m_scanner, childPath));
            } else {
                const ULONGLONG fileSize = (static_cast<ULONGLONG>(findData.nFileSizeHigh) << 32) | findData.nFileSizeLow;

                // 批量处理
                batch.append({fullPath, static_cast<qint64>(fileSize)});
                if (batch.size() >= 200) {
                    m_scanner->submitBatch(batch);
                    batch.clear();
                }
            }
        } while (FindNextFileW(hFind, &findData));

        if (!batch.isEmpty()) {
            m_scanner->submitBatch(batch);
        }


        FindClose(hFind);
    }




private:
    FileScanner* m_scanner;
    QString m_path;
};


//--------------------- FileScanner 实现 ---------------------
FileScanner::FileScanner(QObject *parent)
    : QObject(parent)
{
    // 动态线程池设置
    const int cores = qMax(QThread::idealThreadCount(), 1);
    m_threadPool.setMaxThreadCount(cores * 2);

}

void FileScanner::startScan(const QString &path)
{
    // 路径标准化处理 (Windows专用)
    QString winPath = QDir::toNativeSeparators(path);
    if (!winPath.endsWith("\\*")) {
        if (winPath.endsWith("\\")) {
            winPath += "*";
        } else {
            winPath += "\\*";
        }
    }

    // 提交任务前重置状态
    QMutexLocker locker(&m_mutex);
    m_stopRequested.storeRelaxed(0);
    m_results.clear();
    m_threadPool.start(new ScanTask(this, winPath));
}
FileScanner::~FileScanner()
{
    stopScan();
    m_threadPool.waitForDone(1000);
}
void FileScanner::stopScan()
{
    if (!m_stopRequested.testAndSetRelaxed(0, 1))
        return;

    QMutexLocker locker(&m_mutex);
    // 仅发送未提交的剩余数据（新增临时变量）
       QList<FileResult> uncommitted = m_results.mid(m_lastSubmittedIndex);
       if (!uncommitted.isEmpty()) {
           emit progressBatch(uncommitted);
           m_lastSubmittedIndex = m_results.size(); // 记录已提交位置
       }

    m_threadPool.clear();
    if (!m_threadPool.waitForDone(2000)) {
        qWarning() << "警告：线程池未在指定时间内停止";
    }

   // QMetaObject::invokeMethod(this, [this]() {
  //      emit finished(m_results); // 发送完整的m_results
  //     m_results.clear(); // 清空结果集
   // }, Qt::QueuedConnection);
    // 发送空结果表示扫描终止
       QMetaObject::invokeMethod(this, [this]() {
           emit finished(m_results);
             m_results.clear();
       }, Qt::QueuedConnection);
}

void FileScanner::submitTask(ScanTask* task)
{
    QMutexLocker locker(&m_mutex);
    if (m_stopRequested.loadRelaxed()) {
        delete task;
        return;
    }

    m_threadPool.start(task);
}

void FileScanner::submitBatch(const QList<FileResult>& batch)
{
    QMutexLocker locker(&m_mutex);
      if(m_stopRequested.loadRelaxed()) return;
        m_results.append(batch);
         m_lastSubmittedIndex = m_results.size(); // 更新已提交位置
        emit progressBatch(batch); // 直接发送每个批次


}

//void FileScanner::processData(QList<FileResult> batch)
//{
 //   submitBatch(batch);
//}

//--------------------- 导出函数 ---------------------
FileScanner* createScanner() {
    return new FileScanner;
}

void destroyScanner(FileScanner* scanner) {
    scanner->disconnect(); // 断开所有信号
    scanner->deleteLater(); // 保证事件循环处理,延迟删除，确保事件循环处理完毕
}
